package com.andyliu.interceptor;

import com.andyliu.common.DateUtil;
import com.andyliu.sys.pojo.SActionLog;
import com.andyliu.sys.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * ClassName: ControllerInterceptor
 * Description: TODO
 * date: 2021/2/1 4:54 下午
 *
 * @author andyliu
 * @since JDK 1.8
 */
@Component
public class ControllerInterceptor implements HandlerInterceptor {
    @Autowired
    private LogService logService;

    private long beginDate;
    private long visit;
    private String baseUrl="";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        beginDate = System.currentTimeMillis();
        baseUrl = request.getRequestURI();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        visit = System.currentTimeMillis()-beginDate;
        SActionLog log = new SActionLog();
        log.setUrl(baseUrl);
        log.setVisit(Integer.valueOf((int) visit));
        log.setVisitDate(DateUtil.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        logService.saveActionLog(log);
    }
}
